/**
 * @author: glory.xu
 * @date: 2021/3/12
 * Describe: epg通用js,页面如果需要焦点移动的需要加vitem 样式
 */



Array.prototype.filter || (Array.prototype.filter = function (callback) {
  if (typeof callback !== 'function') {
    throw new TypeError(`${arguments[0]} is not a function!`);
  }
  var context = arguments[1], //this
    arr = this,
    _new = [];
  for (var i = 0; i < arr.length; i++) {
    if (callback.call(context, arr[i], i, arr)) _new.push(arr[i]);
  }
  return _new;
});


var HwEpg;
(function (window) {
    console.log('11111111111111');
    if (HwEpg) return;

    /*
     * 一些通用对象和方法
     */
    var document = window.document;
    var location = window.location;
    var _$ = function (id) {
        return document.getElementById(id);
    };
    var isEmpty = function (str) {
        if (str == undefined || str == "") {
            return true;
        }
        return false;
    };


    /*
     * HwEpg, 页面对象
     */
    HwEpg = {

        defaultGroup: "default-group",
        defaultArea: "default-area",
        gorupId: "default-group", //默认分组ID
        focusId: "",
        focus_class: "active",
        items: [],
        groups: [],
        pointer: {}, //当前指针元素


        initPage() {
            //为每个设置元素设置ID和gorupId
            var evlist = document.getElementsByClassName('vitem');
            for (var i = 0; i < evlist.length; i++) {
                var eletemp = evlist[i];
                var obj = this.getElementInfo(eletemp);
                //如果是图片类型的，添加图片信息
                this.addElement(obj);
            }
            this.pointer = this.items[0];
        },
        //得到元素信息
        getElementInfo: function (eletemp) {
            //如果配了参数就以配了参数的数据
            var eid = eletemp.getAttribute('id');
            var leftId = eletemp.getAttribute('leftId');
            var rightId = eletemp.getAttribute('rightId');
            var upId = eletemp.getAttribute('upId');
            var downId = eletemp.getAttribute('downId');
            var focusCss = eletemp.getAttribute('focusCss');
            var onfocus = eletemp.getAttribute('onfocus');
            var onclick = eletemp.getAttribute('onclick');
            var url = eletemp.getAttribute('url');
            var type = eletemp.getAttribute('type');
            var img = eletemp.getAttribute('img');
            var imgMask = eletemp.getAttribute('imgMask');
            var loadEffect = eletemp.getAttribute('loadEffect'); //加载动画效果 
            var focusEffect = eletemp.getAttribute('focusEffect'); //焦点时动画效果
            var belongGroup = eletemp.getAttribute('belongGroup'); //默认分组

            if (isEmpty(eid)) {
                var eid = "focus-el-" + Math.random().toString(36).replace(/[^a-z]+/g, "").substr(0, 10);
                eletemp.setAttribute('id', eid);
            }
            if (!isEmpty(type) && type === "imageMask") {
                eletemp.innerHTML = "<div class='item'><img   src='" + img + "'/></div><div class='maskImg'><img src='" + imgMask + "'/><div>";
            } else {
                eletemp.innerHTML = "<div class='item'><img  src='" + img + "'/></div><div class='mask'></div>";
            }
            if (!isEmpty(loadEffect)) {
                this.addClass(eletemp, 'animated ' + loadEffect);
            }


            //var obj = {};
            var obj = this.infos(eletemp);
            obj.$el = eletemp;
            obj.id = eid;
            obj.img = img;
            obj.type = type;
            obj.imgMask = imgMask;
            obj.leftId = leftId;
            obj.rightId = rightId;
            obj.upId = upId;
            obj.downId = downId;
            obj.focusCss = focusCss;
            obj.onfocus = onfocus;
            obj.onclick = onclick;
            obj.url = url;
            obj.loadEffect = loadEffect;
            obj.focusEffect = focusEffect;
            obj.belongGroup = belongGroup;
            if (isEmpty(obj.belongGroup)) {
                obj.belongGroup = this.defaultGroup;
            }
            if (isEmpty(obj.belongArea)) {
                obj.belongArea = this.defaultArea;
            }
            return obj;

        },
        addElement: function (element) {

            this.items.push(element);
            var group = element.belongGroup;
            this.groups.push(group)
        },

        //是否包含css
        hasClass(elements, cName) {
            return !!elements.className.match(new RegExp("(\\s|^)" + cName + "(\\s|$)")); // ( \\s|^ ) 判断前面是否有空格 （\\s | $ ）判断后面是否有空格 两个感叹号为转换为布尔值 以方便做判断
        },
        //添加css
        addClass(elements, cName) {
            if (!this.hasClass(elements, cName)) {
                elements.className += " " + cName;
            }
        },
        //移除css
        removeClass(elements, cName) {
            if (this.hasClass(elements, cName)) {
                elements.className = elements.className.replace(new RegExp("(\\s|^)" + cName + "(\\s|$)"), " "); // replace方法是替换
            }
        },

        //以下为计算
        //获取坐标信息
        infos(target) {
            var info;
            try {
                info = target.getBoundingClientRect();
            } catch (e) {
                console.log('no bounding', target)
                return false
            }
            return {
                left: info.left,
                right: info.left + info.width,
                up: info.top,
                down: info.top + info.height,
                x: info.x,
                y: info.y
            };
        },
        //
        distance(cx, cy, nx, ny) {
            return parseInt(Math.sqrt(Math.pow(cx - nx, 2) + Math.pow(cy - ny, 2)));
        },
        contains(cmin, cmax, nmin, nmax) {
            return (cmax - cmin) + (nmax - nmin) >= Math.max(cmin, cmax, nmin, nmax) - Math.min(cmin, cmax, nmin, nmax);
        },
        rules(pinfo, ninfo, pDvalue, mDvalue, dir) {
            var tmp, pref, min;
            if (dir === 'up') {
                if (pinfo.up >= ninfo.down) {
                    tmp = this.distance(ninfo.left, ninfo.up, pinfo.left, pinfo.up);
                    (!mDvalue || tmp < mDvalue) && (mDvalue = tmp, min = true);
                    (!pDvalue || this.contains(ninfo.left, ninfo.right, pinfo.left, pinfo.right) && tmp < pDvalue) && (pDvalue = tmp, pref = true);
                }
            } else if (dir === 'down') {
                if (pinfo.down <= ninfo.up) {
                    tmp = this.distance(ninfo.left, ninfo.up, pinfo.left, pinfo.up);
                    (!mDvalue || tmp < mDvalue) && (mDvalue = tmp, min = true);
                    (!pDvalue || this.contains(ninfo.left, ninfo.right, pinfo.left, pinfo.right) && tmp < pDvalue) && (pDvalue = tmp, pref = true);
                }
            } else if (dir === 'left') {
                if (pinfo.left >= ninfo.right) {
                    tmp = this.distance(ninfo.left, ninfo.up, pinfo.left, pinfo.up);
                    (!mDvalue || tmp < mDvalue) && (mDvalue = tmp, min = true);
                    (!pDvalue || this.contains(ninfo.up, ninfo.down, pinfo.up, pinfo.down) && tmp < pDvalue) && (pDvalue = tmp, pref = true);
                }
            } else if (dir === 'right') {
                if (pinfo.right <= ninfo.left) {

                    tmp = this.distance(ninfo.left, ninfo.up, pinfo.left, pinfo.up);
                    (!mDvalue || tmp < mDvalue) && (mDvalue = tmp, min = true);
                    (!pDvalue || this.contains(ninfo.up, ninfo.down, pinfo.up, pinfo.down) && tmp < pDvalue) && (pDvalue = tmp, pref = true);
                }
            }
            return {
                pDvalue: pDvalue,
                mDvalue: mDvalue,
                pref: pref,
                min: min
            };
        },
        getGroup() {
            return this.gorupId;
        },
        setGroupId(groupId) {
            this.groupId = groupId;
        },
        getFoucsClass() {
            var focus_class = this.pointer.focus_class || this.focus_class;
            return focus_class;
        },
        getItem(vnode) {
            var elm = vnode.elm;
            var id = "focus-el-" + Math.random().toString(36).replace(/[^a-z]+/g, "").substr(0, 10);
        },
        //查找下一个坐标信息
        next(dir) {
            var pointer = this.pointer,
                pinfo = this.infos(this.pointer.$el);
            //如果y坐标小于50返回null
            console.log(pinfo.x);
            if (dir === "left" && pinfo.x < 50) {
                console.log('边界left')
                return false;
            }
            if (dir === "right" && pinfo.right > 1250) {
                console.log('边界right')
                return false;
            }
            //按向左，先查找本行相邻的一个元素,y坐标相同，x<当前
            if (dir === "left") {
                var maxid = -1;
                var tempX = 0;
                if (this.items.length > 0) {
                    for (var t = 0; t < this.items.length; t++) {
                        if (this.items[t].y == pointer.y && this.items[t].x < pointer.x && this.items[t].x > tempX) {
                            tempX = this.items[t].x;
                            maxid = t;
                        }
                    }
                    if (maxid > -1) { //找到了
                        return this.items[maxid];
                    }
                }
            }
            //向右
            if (dir === "right") {
                var maxid = -1;
                var tempX = 99999;
                if (this.items.length > 0) {
                    for (var t = 0; t < this.items.length; t++) {
                        if (this.items[t].y == pointer.y && this.items[t].x > pointer.x && this.items[t].x < tempX) {
                            tempX = this.items[t].x;
                            maxid = t;
                        }
                    }
                    if (maxid > -1) { //找到了
                        return this.items[maxid];
                    }
                }
            }

            //如果以上没找到，然后按距离查找
            var ninfo, pDvalue, mDvalue, pref, min;
            this.items.forEach(function (item, index) {
                if (item !== pointer) {
                    ninfo = this.infos(item.$el, dir);
                    var rule = this.rules(pinfo, ninfo, pDvalue, mDvalue, dir);
                    pDvalue = rule.pDvalue;
                    mDvalue = rule.mDvalue;
                    rule.pref && (pref = item);
                    rule.min && (min = item);
                }
            }.bind(this));

            if (dir === "left" || dir === "right") {
                return pref;
            } else if (dir === "up" || dir === "down") {
                return pref || min;
            }
        },
        //移动到位置
        move(target) {
            if (!this.items.length) return;
            !this.pointer && (this.pointer = this.items[0]);
            var next, nextGroup, type = typeof target;
            !target && (target = this.pointer);
            if (type === "object") {
                if (target.$el) {
                    target = target.$el;
                }
            }
            //查找下一个元素,判断是移到上下左右还是到特定元素
            if (type === "object") {

                var arr = this.items.filter(function (item, inde, array) {
                    return item.id === target.id;
                })

                next = arr[0]; // this.items.filter(item => item.id === target.id)[0];


            } else if (/up|down|right|left/gi.test(target)) {
                //console.log("up down right left");
                //如果配了上下左右的id就跳那边去
                var tid = "";
                if (/up/gi.test(target)) {
                    tid = this.pointer.upId;
                }
                if (/down/gi.test(target)) {
                    tid = this.pointer.downId;
                }
                if (/right/gi.test(target)) {
                    tid = this.pointer.rightId;
                }
                if (/left/gi.test(target)) {
                    tid = this.pointer.leftId;
                }
                //如果方向ID不为空，到相应的ID里去
                if (isEmpty(tid)) {
                    next = this.pointer && this.next(target);
                } else {
                    var p = this.getElementInfo(document.getElementById(tid))
                    next = this.pointer && p;
                }

            }

            if (next) {

                if (this.pointer) {
                    this.pointer.isFocus = false;
                    this.removeClass(this.pointer.$el, this.getFoucsClass());

                    //移除效果动画
                    if (!isEmpty(this.pointer.focusEffect)) {
                        this.removeClass(this.pointer.$el, 'animated ' + this.pointer.focusEffect);
                    }
                    //
                }
                this.pointer = next;
                this.pointer.isFocus = true;
                this.addClass(this.pointer.$el, this.getFoucsClass());

                //开始效果动画
                if (!isEmpty(this.pointer.focusEffect)) {
                    this.addClass(this.pointer.$el, 'animated ' + this.pointer.focusEffect);
                }
            }
        },
        onOk: function () {
            var element = this.pointer;
            console.log(this.pointer);
            if (element && element.url) {
                var url = element.url;

                if (/\?$/.test(url)) {
                    url += 'focusid=' + this.focusId + '&gfocusid=' + this.getGFocus();
                } else if (/\?.+$/.test(url)) {
                    url += '&focusid=' + this.focusId + '&gfocusid=' + this.getGFocus();
                } else {
                    url += '?focusid=' + this.focusId + '&gfocusid=' + this.getGFocus();
                }
                location.href = url;
            }
        },
        updateScroll: function () {
            var grid = document.getElementById('page')
            var scroll = this.pointer.$el.offsetTop;
            var h = this.pointer.$el.offsetHeight

            var s1 = (scroll + this.pointer.$el.offsetHeight) % 720;
            var s2 = (scroll % 720);
            grid.scrollTop = scroll - 50


        },
        onBack: function () {
            console.log('--back--')
        },
        clear() {
            this.pointer = false;
            this.groups = [];
            this.items = [];
        },
        getGFocus() {



            return '';
        }

        //end
    }




    var gloabtime = new Date().getTime();
    // 键盘事件监听
    document.onkeydown = function (event) {
        var e = event || window.event || arguments.callee.caller.arguments[0];
        var nowTime = new Date().getTime();
        //console.log(nowTime);
        //防止按键太快
        if (nowTime - gloabtime < 100) {
            gloabtime = nowTime;
            return false;
        }
        gloabtime = nowTime;
        if (e && e.keyCode == 40) { //下
            HwEpg.move('down');
        }

        if (e && e.keyCode == 37) { //左
            HwEpg.move('left');
        }
        if (e && e.keyCode == 39) { //右
            HwEpg.move('right');
        }
        if (e && e.keyCode == 38) { // 上
            HwEpg.move('up');
        }
        if (e && e.keyCode == 13) { // 确定
            HwEpg.onOk();
        }
        if (e && (e.keyCode == 27 || e.keyCode == 7 || e.keyCode == 8)) { //返回
            //HwEpg.onBack();
            //exec('back()');
            eval('back()')
        }
        //滚动页面
        HwEpg.updateScroll();
        return false;
    }
})(window);
